package cs4280.ass2.persistence;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import cs4280.ass2.entity.Manager;
import cs4280.ass2.entity.Member;
import cs4280.ass2.entity.Officer;
import cs4280.ass2.entity.User;

public class UserDao extends BaseDao {
	private static final Logger logger = Logger.getLogger(UserDao.class);
	private static final String _SELECT_BY_ID = "select * from APP_USER where LOGIN = ? and PASSWORD = ?";

	private static UserDao userDao = null;

	public static UserDao getInstance() {
		if (userDao == null) {
			userDao = new UserDao();
		}
		return userDao;
	}

	public User retrieveUserByLoginPwd(String login, String password) {
		User user = null;
		Connection connection = null;
		PreparedStatement statement = null;
		ResultSet result = null;

		try {
			connection = getConnection();
			statement = connection.prepareStatement(_SELECT_BY_ID, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
			statement.setString(1, login);
			statement.setString(2, password);
			result = statement.executeQuery();
			if (result.next()) {
				if (StringUtils.equals(result.getString("type"), User.USER_TYPE_MANAGER)) {
					user = new Manager();
				} else if (StringUtils.equals(result.getString("type"), User.USER_TYPE_MEMBER)) {
					user = new Member();
					Member member = (Member) user;
					member.setLoyaltyPoint(result.getDouble("loyalty_point"));
				} else if (StringUtils.equals(result.getString("type"), User.USER_TYPE_OFFCIER)) {
					user = new Officer();
				}

				user.setId(result.getLong("id"));
				user.setFirstName(result.getString("first_name"));
				user.setLastName(result.getString("last_name"));
				user.setLogin(result.getString("login"));
				user.setPassword(result.getString("password"));
				user.setType(result.getString("type"));
				user.setAppUserStatus(result.getString("APP_USER_STATUS"));
				user.setCreateDate(toUtilDate(result.getTimestamp("create_date")));
				user.setCreateUser(result.getLong("create_user"));
				user.setModifyDate(toUtilDate(result.getTimestamp("modify_date")));
				user.setModifyUser(result.getLong("modify_user"));
			}
		} catch (SQLException e) {
			logger.error("Fail to retrieveMember ", e);
		} finally {
			DbUtils.closeQuietly(result);
			DbUtils.closeQuietly(statement);
			DbUtils.closeQuietly(connection);
		}
		return user;
	}
}
